﻿using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace DynamicGeometry
{
    public class DivideSegmentCreator : FigureCreator
    {
        protected override DependencyList InitExpectedDependencies()
        {
            return DependencyList.PointPoint;
        }

        protected override IFigure CreateFigure()
        {
            Point pt1 = (FoundDependencies[0] as IPoint).Coordinates;
            Point pt2 = (FoundDependencies[1] as IPoint).Coordinates;
            IntermediateFigure = Drawing.Figures.FindLine((FoundDependencies[0] as IPoint), (FoundDependencies[1] as IPoint)) as Segment;
            FreePoint result = Factory.CreateFreePoint(Drawing, new Point(
                                                (pt1.X + pt2.X) / 2,
                                                (pt1.Y + pt2.Y) / 2));
            return result;
        }

        public override void MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var underMouse = Drawing.Figures.HitTest<Segment>(Coordinates(e));
            if (underMouse != null
                && underMouse.Dependencies.Count() == 2
                && Drawing.Figures.HitTest<IPoint>(Coordinates(e)) == null)
            {
                FoundDependencies = new FigureList(underMouse.Dependencies);
            }
            base.MouseDown(sender, e);
        }

        /// <summary> 
        /// </summary>
        protected override void CreateAndAddFigure()
        {
            base.CreateAndAddFigure();
            for (int i = 0; i < FoundDependencies.Count; i++)
            {
                int j = (i + 1) % FoundDependencies.Count;
                IPoint p1 = FoundDependencies[i] as IPoint;
                IPoint p2 = TempResult as IPoint;
                if (Drawing.Figures.FindLine(p1, p2) == null)
                {
                    Segment segment = Factory.CreateSegment(Drawing, new FigureList() { p1, p2 });
                    Drawing.Add(segment);
                }
            }
        }

        public override string Name
        {
            get { return "Divide segment"; }
        }

        public override string HintText
        {
            get
            {
                return "Click a segment to construct a midpoint and to divide the segment in two.";
            }
        }

        public override FrameworkElement CreateIcon()
        {
            return IconBuilder.BuildIcon()
                .Line(0.25, 0.75, 0.4, 0.4)
                .Line(0.4, 0.4, 0.75, 0.25)
                .Point(0.25, 0.75)
                .Point(0.4, 0.4)
                .Point(0.75, 0.25)
                .Canvas;
        }
    }
}